package org.example.foodhealth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class VerificationCode {
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final Random RANDOM = new SecureRandom();

    // 生成 6 位验证码
    public String generateVerificationCode() {
        StringBuilder code = new StringBuilder(6);
        for (int i = 0; i < 6; i++) {
            code.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length())));
        }
        return code.toString();
    }

    // 发送验证码到用户邮箱
    public void sendVerificationCode(String email) {
        String code = generateVerificationCode();
        sendEmail(email, code);
        redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES); // 过期时间 5 分钟
    }

    // 发送邮件
    private void sendEmail(String email, String code) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("178956409@qq.com"); // 确保发件人地址与授权用户一致
        message.setTo(email);
        message.setSubject("Your Verification Code");
        message.setText("Your verification code is: " + code);
        mailSender.send(message);
    }

    // 验证用户输入的验证码
    public boolean verifyCode(String email, String code) {
        String storedCode = redisTemplate.opsForValue().get(email);
        return code.equals(storedCode);
    }

    // 保存验证码验证成功的状态
    public void saveValidCode(String email) {
        redisTemplate.opsForValue().set(email + ":verified", "true", 5, TimeUnit.MINUTES); // 设置过期时间
    }

    // 检查验证码验证状态
    public boolean checkValidCode(String email) {
        return "true".equals(redisTemplate.opsForValue().get(email + ":verified"));
    }

    // 注销验证码的有效状态
    public void invalidateCode(String email) {
        redisTemplate.delete(email + ":verified");
    }
}
